package zhibi.cms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhibi.cms.domain.Menu;
import zhibi.cms.extra.base.BaseServiceImpl;
import zhibi.cms.extra.pojo.MenuPo;
import zhibi.cms.mapper.MenuMapper;
import zhibi.cms.service.MenuService;
import zhibi.commons.exception.MessageException;
import zhibi.frame.domain.Page;
import zhibi.frame.mybatis.example.Example;
import zhibi.frame.mybatis.example.ExampleType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {

    @Autowired
    public MenuServiceImpl(MenuMapper mapper) {
        super(mapper);
        this.menuMapper = mapper;
    }

    private MenuMapper menuMapper;

    @Override
    public PageInfo<MenuPo> selectPoByExample(Example example, Page page) {
        if (null != page) PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return new PageInfo<>(menuMapper.selectPoByExample(example), Page.NAV_SIZE);
    }

    @Override
    public List<Menu> selectByPid(String pid) {
        Menu menu = new Menu();
        menu.setPid(pid);
        return menuMapper.select(menu);
    }

    @Override
    public Map<String, Object> selectTreeByPid(String pid) {
        Menu menu = menuMapper.selectByPrimaryKey(pid);
        if (menu == null) throw new MessageException("该菜单不存在");
        Example example = Example.getInstance()
                .addOrder("sort", ExampleType.OrderType.DESC)
                .addParam("pid", pid)
                .addParam("status", 1);
        List<Menu> menuList = menuMapper.selectByExample(example);
        Map<String, Object> map = new HashMap<>();
        map.put("parent", menu);
        map.put("child", menuList);
        return map;
    }
}
